package com.mali.backendcommon.interceptor;

import cn.hutool.json.JSONUtil;
import com.mali.backendcommon.constant.MessageConstant;
import com.mali.backendcommon.properties.JwtProperties;
import com.mali.backendcommon.util.JwtUtil;

import com.mali.backendcommon.util.RedisUtil;
import com.mali.backendcommon.util.UserContext;
import com.mali.malibackendmodel.pojo.User;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.rmi.MarshalException;
import java.util.Optional;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private  RedisUtil redisUtil;
    private final String loginUser="loginUser";

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //2.从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());
        if (token == null || token.isEmpty()) {
            response.setStatus(401);
            return false;
        }
        //3.校验并解析token
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            String jti = claims.get("jti", String.class);
            //检验token是否在黑名单
            Optional<Object> optionalValue = Optional.ofNullable(redisUtil.get(jti));
            int isBlacklistedToken = (int) optionalValue.orElse(0);
            //在黑名单 拦截
            if(isBlacklistedToken==1){
                response.setStatus(401);
                return false;
            }
            String userStr= claims.get(loginUser).toString();
            User user = JSONUtil.toBean(userStr, User.class);
            //4.存储在ThreadLocal
            UserContext.setUser(user);
            log.info("当前登录用户：{}", user);
            return true;
        } catch (Exception e) {
            //5.不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户 防止内存泄漏
        UserContext.removeUser();
    }

}
